<?php

function observation_validator_form() {
  $func_args = func_get_args();
  if (count($func_args) == 0) {
    global $user;
    $uid = $user->uid;
  }
  else {
    $uid = (int)$func_args[0];
    if ($uid == 1) { // If some other user tries to access request page as admin
      drupal_goto('observation/validator_request');
    }
  }
  if ($uid == 1) {
    $html = <<<EOT
    <div class="messages error">You are the site admin. You don't need to fill a form to validate. </div>
EOT;
  }
  else {
    global $user;
    if (user_access('administer win_observation') || $user->uid == $uid) {
      $html = show_validtor_request_form($uid);
    }
    else {
      $html = '<div class="messages error">You are not authorized.</div>';
    }
  }
  return $html;
}

function show_validtor_request_form($uid) {
  $html = '';

  $user_details = '';
  global $user;
  if ($user->uid != $uid) {
    $path = drupal_get_path('module','win_observation');
    drupal_add_js($path . '/js/external/jquery-1.3.2.js');
    drupal_add_js($path . '/js/functions.js');
    drupal_add_js($path . '/js/validation/win_validation_display.js');

    drupal_add_js('var uid = ' . $uid . ';', 'inline');

    $result = db_query('select name from {users} where uid = %d', array($uid));
    if (!$result) {
    }
    else {
      if ($obj = db_fetch_object($result)) {
        $user_details = '<div>Request by: <a href="' . base_path() . 'user/' . $uid . '" target="_blank">' . $obj->name . '</a></div>';
      }
    }
    $html .= $user_details;
    
    $html .= <<<EOT
    <div id="divValidationRequest">
      <fieldset id="fsLanguages">
        <legend>Languages</legend>
        <div id="divLanguages">
        </div>
      </fieldset>
      <fieldset id="fsSciTerms">
        <legend>Taxanomy</legend>
        <div id="divTaxanomies">
        </div>
      </fieldset>
      <fieldset id="fsEcosystems">
        <legend>Ecosystems</legend>
        <div id="divEcosystems">
        </div>
      </fieldset>
      <fieldset id="fsWaterbodies">
        <legend>Waterbodies</legend>
        <div id="divWaterbodies">
        </div>
      </fieldset>
      <fieldset id="fsLocations">
        <legend>Locations</legend>
        <div id="divLocations">
        </div>
      </fieldset>
    </div>
EOT;

    if (user_access('administer win_observation')) {
      $html .= <<<EOT
      <div style="text-align:center">
        <input type="hidden" id="uid" value="{$uid}" />
        <div>
          Status:
          <select name="status">
            <option value="0">Pending</option>
            <option value="1">Approved</option>
            <option value="2">Rejected</option>
          </select>
        </div>
        <div>
          Comments:
          <textarea name="comments" cols="100" rows="5"></textarea>
        </div>
        <div>
          <input type="button" id="btnUpdateStatus" value="Update" />
        </div>
      </div>
EOT;
    }
  }
  else {
    $path = drupal_get_path('module','win_observation');
    drupal_add_js($path . '/js/external/jquery-1.3.2.js');
    drupal_add_js($path . '/js/external/jquery.selectboxes.js');
    drupal_add_js($path . '/js/functions.js');
    drupal_add_js($path . '/js/validation/win_validation_request_form.js');
    drupal_add_css($path . '/css/jquery-ui.css');
    drupal_add_css($path . '/css/validation/win_validation_request_form.css');

    drupal_add_js('var uid = ' . $uid . ';', 'inline');

    $countries_list = get_countries_list();

    $application_msg = '';
    if ($uid > 0) {
      $result = db_query('select status, comments from win_validators where uid = %d;', array($uid));
      if (!$result) {
      }
      else {
        if ($obj = db_fetch_object($result)) {
          $comments = empty($obj->comments) ? '' : '<ul><li>' . $obj->comments . '</ul>';
          switch ($obj->status) {
            case 0:
              $application_msg = <<<EOT
                <div class="messages warning">
                  This request has not yet been processed. <div>{$comments}</div>
                </div>
EOT;
              drupal_add_js('var requestApproved=false;', 'inline');
              break;
            case 1:
              $application_msg = <<<EOT
                <div class="messages status">
                  This request has been accepted. <div>{$comments}</div>
                </div>
EOT;
              drupal_add_js('var requestApproved=true;', 'inline');
              break;
            case 2:
              $application_msg = <<<EOT
                <div class="messages error">
                  This request has been rejected. <div>{$comments}</div>
                </div>
EOT;
              drupal_add_js('var requestApproved=false;', 'inline');
              break;
          }
        }
      }
    }
    
    $base_path = base_path();

    $html = <<<EOT
    <div class="messages warning">
      If you have expertise in a particular area and would like to help us validate contributions, please fill in the following form and we will get back to you.
    </div>

    {$application_msg}

    <div id="divValidationRequest">
      <fieldset id="fsLanguages">
        <legend>Languages</legend>
        <div id="divLanguage">
          Language: <input name="language" type="textbox" size="20"/>
        </div>
        <div id="divMoreLanguages">
          <input id="btnMoreLanguages" type="button" value="More" />
        </div>
      </fieldset>
      <fieldset id="fsSciTerms">
        <legend>Taxanomy</legend>
        <div>
          <div>
            Kingdom: <select id="selKingdom"></select>
          </div>
          <div class="hidden">
            Phylum: <select id="selPhylum"></select>
          </div>
          <div class="hidden">
            Class: <select id="selClass"></select>
          </div>
          <div class="hidden">
            Order: <select id="selOrder"></select>
          </div>
          <div class="hidden">
            Family: <select id="selFamily"></select>
          </div>
          <div class="hidden">
            Genus: <select id="selGenus"></select>
          </div>
          <div class="hidden">
            Species: <select id="selSpecies"></select>
          </div>
        </div>
        <div>
          <input id="btnAddTaxanomy" type="button" value="Add" />
        </div>
        <div id="divTaxanomies">
        </div>
      </fieldset>
      <fieldset id="fsEcosystems">
        <legend>Ecosystem</legend>
        <div id="divEcosystem">
          <div>
            <select id="parent_ecosystem"></select>
          </div>
          <div class="hidden">
            <select id="child_ecosystem"></select>
          </div>
        </div>
        <div>
          <input id="btnAddEcosystem" type="button" value="Add" />
        </div>
        <div id="divEcosystems">
        </div>
      </fieldset>
      <fieldset id="fsWaterbodies">
        <legend>Waterbodies</legend>
        <div id="divWaterbody">
          <select name="waterbody_type">
            <!-- <option value="none">None</option> -->
            <option value="Ocean">Ocean</option>
            <option value="Lake">Lake</option>
            <option value="River">River</option>
            <option value="All">All</option>
          </select>
          <input type="textbox" name="waterbody_name" size="25" />
          <span style="font-size: 0.85em; margin-left: 10px; font-style: italic; color: #898989;">Enter the name of the waterbody. Enter 'All' for all waterbodies of a type.</span>
        </div>
        <!--
        <div id="divMoreWaterbodies">
          <input id="btnMoreWaterbodies" type="button" value="More" />
        </div>
        -->
        <div>
          <input id="btnAddWaterbody" type="button" value="Add" />
        </div>
        <div id="divWaterbodies">
        </div>
      </fieldset>
      <fieldset id="fsLocations">
        <legend>Locations</legend>
        <div id="divLocation" name="divLocation">
          <div>
            Country: <select id="country" name="country">
EOT;
    $html .= createDropdownOptions($countries_list);
    $html .= <<<EOT
            </select>
          </div>
          <div class="hidden">
            Region/ State: <select id="region" name="region">
            </select>
          </div>
          <div class="hidden">
            City: <select id="city" name="city">
            </select>
          </div>
        </div>
        <div>
          <input id="btnAddLocation" type="button" value="Add" />
        </div>
        <div id="divLocations">
        </div>
      </fieldset>
      <fieldset>
        <legend>Captcha</legend>
        <div class="form-item">
          <div>
            <img id="wo_captcha" src='{$base_path}observation/data/{"action":"getCaptchaImage"}'></img>
            <input type="button" id="wo_reload_captcha" value="Reload" class="form-submit" onclick="reloadCaptcha('wo_captcha')"/>
          </div>
          <input type="text" maxlength="5" name="wo_captcha" id="edit-wo-captcha" size="10" value="" class="form-text required" />
          <span class="form-required" title="' .  t('This field is required.') . '">*</span>
          <div class="description">
EOT;
    $html .= t('Enter the characters that you see above.');
    $html .= <<<EOT
    </div>
        </div>
      </fieldset>
      <div style="text-align:center">
        <input type="button" value="Submit" id="btnSubmit" />
      </div>
    </div>
EOT;
  }

  return $html;
}

function createDropdownOptions($list) {
  $options = '';
  foreach ($list as $id => $name) {
    $options .= '<option value="'.$id.'">'.t($name).'</option>';
  }
  return $options;
}

function submit_validation_request($params) {
  $languages = $params['languages'];
  $location = $params['location'];
  $taxanomy = $params['taxanomy'];
  $ecosystem = $params['ecosystem'];
  $waterbodies = $params['waterbodies'];
  $captcha = $params['captcha'];

  global $user;
  $uid = $user->uid;
  if ($uid == 0) {
    die(json_encode(set_error_arr("You are not authorized.")));
  }

  if ($_SESSION['win_captcha_code'] != $captcha) {
    die(json_encode(set_error_arr("The string entered does not match the captcha image.")));
  }

  $args = array();
  foreach ($languages as $lang) {
    $args[] = array($uid, 'language', $lang);
  }

  foreach ($location as $loc) {
    $args[] = array($uid, 'location', $loc);
  }

  foreach ($taxanomy as $taxa) {
    $args[] = array($uid, 'taxanomy', $taxa);
  }

  foreach ($ecosystem as $eco) {
    $args[] = array($uid, 'ecosystem', $eco);
  }

  // foreach ($waterbodies as $waterbody) {
    // $args[] = array($uid, 'waterbody', $waterbody['type'] . ':' . $waterbody['name']);
  // }
  foreach ($waterbodies as $wb) {
    $args[] = array($uid, 'waterbody', $wb);
  }

  $query_args = array();
  $query = 'BEGIN;';
  $query .= 'delete from win_validator_expertise where uid = %d;';
  $query_args = array_merge($query_args, array($uid));
  $query .= 'delete from win_validators where uid = %d;';
  $query_args = array_merge($query_args, array($uid));

  foreach ($args as $arg) {
    $query .= "insert into win_validator_expertise (uid, expertise_type, expertise_mapping) values (%d, '%s', '%s');";
    $query_args = array_merge($query_args, $arg);
  }

  $query .= 'insert into win_validators (uid, status) values (%d, 0);';
  $query_args = array_merge($query_args, array($uid));

  $query .= 'COMMIT;';

  $result = db_query($query, $query_args);
  if (!$result) {
    die(json_encode(set_error_arr("Error registering your request. Please try after sometime.")));
  }
  else {
    die(json_encode(set_no_error_arr("Thank you for your interest. Your request has been submitted. We will be get back to you soon.")));
  }
}